package com.jjyd.crlp.interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.jjyd.crlp.model.code.CommonConst;
import com.jjyd.crlp.model.code.CommonErrorCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 登陆拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    // 定义一个线程域，存放登录用户
    private static final ThreadLocal<Integer> tl = new ThreadLocal<>();
    /**
     * 前置拦截controller
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

        //得到所有的上送参数
        Map<String, String[]> map = httpServletRequest.getParameterMap();
//        String userId = map.get("userId")[0];
        String token = map.get("token")[0];

        String key = CommonConst.PARAM_DIGEST;
        Algorithm alg = Algorithm.HMAC256(key);


        // 2 验证Token
        JWTVerifier verifier = JWT.require(alg)
                .withIssuer(CommonConst.ISSUER)
                .withAudience(CommonConst.AUDIENCE)
                .build();
        try{
            verifier.verify(token);
            System.out.println("验证通过!");
        } catch (JWTVerificationException e) {
            e.printStackTrace();
            //设置编码格式
            httpServletResponse.setCharacterEncoding("UTF-8");
            //这句话是解决乱码的
            httpServletResponse.setHeader("Content-Type", "application/json;charset=UTF-8");
            httpServletResponse.getWriter().print("{\"errorCode\": \"" + CommonErrorCode.NO_LOGIN + "\",\"errorMessage\": \"未登陆\",\"data\": null}");
            System.out.println("验证失败!");
            return false;
        }


//        // 3 尝试解码
//        try{
//            DecodedJWT originToken = JWT.decode(token);
//            System.out.println("解码得到发行者是:"+originToken.getIssuer());
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            System.out.println("解码得到签发时间是:"+sdf.format(originToken.getIssuedAt()));
//            System.out.println("解码得到到期时间是:"+sdf.format(originToken.getExpiresAt()));
//            System.out.println("解码得到公共域信息是:"+originToken.getClaim("PublicClaimExample").asString());
//        } catch (JWTDecodeException e){
//            e.printStackTrace();
//        }

        try {
            DecodedJWT originToken = JWT.decode(token);
            String subject = originToken.getSubject();
            Integer userId = Integer.valueOf(subject);
            tl.set(userId);
        } catch (JWTDecodeException e) {
            // 抛出异常，证明未登录,返回401
            httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }


        return true;


    }



    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //程序运行结束之后，删除线程???（删除Value）
        tl.remove();
    }

    public static Integer getUserId() {
        return tl.get();
    }

}
